import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *





def _Find_input_element(driver:WebDriver,label:str) -> WebElement:
    anchor_element = driver.find_elements(by=By.XPATH,value=f"//*[(self::span or self::label or self::div) and text()='{label}']")
    if len(anchor_element) == 1:
        find_xpath_path = "./parent::*//input"
        while True:
            try:
                element = anchor_element[0].find_element(by=By.XPATH,value=find_xpath_path)
                return element
            except NoSuchElementException:
                print(f"提示 : 当前层级没有找到 Input 元素,继续向上查找!")
                find_xpath_path = find_xpath_path.replace("//input","/parent::*//input")
                continue





def print_with_time(*args, **kwargs) -> None:
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)








def On_InputPage_Input_Batch_Price_And_Code(driver:WebDriver,Number:int,Price:float,Product_Code):
    """批量设置价格.
    """
    
    # 1.定位到设置 价格 库存 编码的位置
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,"//button/span[text()='更多批量']")))
        
        # 打开填充的 【对话框】
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            
        # 验证是否出现 【对话框】
        try:
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@role='dialog']/div[text()='批量填充']")))
        except TimeoutException:
            print_with_time(f"提示 : 没有在规定的时间内检测到 【批量填充】 的对话框!")
        
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [价格] 输入框元素!")

    # 2.设置价格
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./span[text()='价格'] and .//input[@id='skuPrice']]//input[@id='skuPrice']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Price)
        
        try:
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//div[./span[text()='价格'] and .//input[@id='skuPrice']]//input[@id='skuPrice']"),text_=str(Price)))
        except TimeoutException:
            print_with_time(f"提示 : 检测到 【价格】 输入框值未更新!")
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 【价格】 输入框元素!")
    
    # 3.设置库存
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./span[text()='数量'] and .//input[@id='skuStock']]//input[@id='skuStock']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Number)
        
        try:
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//div[./span[text()='数量'] and .//input[@id='skuStock']]//input[@id='skuStock']"),text_=str(Number)))
        except TimeoutException:
            print_with_time(f"提示 : 检测到 【库存】 输入框值未更新!")
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 【库存】 输入框元素!")
        
    # 4.设置编码
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./span[text()='商家编码'] and .//input[@id='skuOuterId']]//input[@id='skuOuterId']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Product_Code)
        
        try:
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//div[./span[text()='商家编码'] and .//input[@id='skuOuterId']]//input[@id='skuOuterId']"),text_=str(Product_Code)))
        except TimeoutException:
            print_with_time(f"提示 : 检测到 【商家编码】 输入框值未更新!")
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 【商家编码】 输入框元素!")
        
    # 5.提交填写的信息
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//button/span[text()='批量填充']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)\
        
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [批量填充] 的按钮元素选项!")

    # 6.填写外部的商家编码
    try:
        xpath_value = f"//div[@id='struct-outerId']//input[@value='']"
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located(locator=(By.XPATH,xpath_value)))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Product_Code)
    except TimeoutException:
        print_with_time(f"提示: 没有找到 [商家编码] 输入框元素!")
    
    # try:
    #     element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,"//input[contains(@dropdownclassname,'每个用户累计可购买')]")))
    #     driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
    #     while element.get_attribute("value"):
    #         element.send_keys(Keys.BACKSPACE*20)
    #     element.send_keys("3")
    # except TimeoutException:
    #     print(f"提示: 没有找到 [每个用户累计可购买] 输入框元素!")